﻿var _helper;
function Helper()
{
	//私有变量
	var __templates = [];
	
	//初始化指定标签页面
	this.init = function(element, index, nav)
	{
		//url
		var url;
		if (nav)
			url = nav;
		else
			url = ali.navTab(element, 'getUrl', index);
		
		//template
		var template = null;
		var index = url.indexOf(_channelPath);
		var pathInChannel = url.substr(index + _channelPath.length - 1);
		var instanceId = pathInChannel.match(/\/\d+\//)[0];
		index = pathInChannel.indexOf(instanceId);
		var templatePath = pathInChannel.substr(index + instanceId.length - 1);
		var pageIndex = templatePath.lastIndexOf('/page/');
		templatePath = templatePath.substr(0, pageIndex + 1);
		for (i = 0; i < __templates.length; i++)
		{
			if (__templates[i].path == templatePath)
				template = __templates[i];
		}
		
		//如果第一次使用该模板，则添加到缓存
		if (!template)
		{
			template = {path:templatePath,dict:null,init:null}
			__templates.push(template);
			
			//加载词典
			var dict = template.path + 'dictionary/' + _lang + '.js';
			$.ajax(
			{
				url: dict,
				type: 'GET',
				dataType: 'json',
				async: false,
				success: function(data)
				{
					template.dict = data;
				}
			});
			
			//加载脚本
			var js = template.path + 'js/module.js';
			$('body').append('<script src="' + js + '">');
		}

		//获取页面名称
		var panel,page;
		if (nav)
		{
			panel = $('.frame1-left .ali-panel-body');
			page = 'nav';
		}
		else
		{
			panel = ali.navTab(element, 'getPanel', index);
			page = $('>section', panel).data('page');
		}

		//初始化页面
		template.init(instanceId.substr(1, instanceId.length - 2), page, panel, url);
	};
	
	this.addInit = function(path, init)
	{
		for (var i = 0; i < __templates.length; i++)
		{
			if (__templates[i].path == path)
				__templates[i].init = init;
		}
	};
	
	this.dict = function(path, key)
	{
		for (var i in __templates)
		{
			if (__templates[i].path == path)
			{
				for (var name in __templates[i].dict)
				{
					if (key == name)
						return __templates[i].dict[name];
				}
			}
		}
		return key;
	};
	
	this.get = function(options)
	{
		return send($.extend(options, {type:'GET',silent:true}));
	};

	this.post = function(options)
	{
		return send($.extend(options, {type:'POST'}));
	};

	this.update = function(instance, object, element, id, operation, callback)
	{
		if (id)
		{
			send({instance:instance,object:object,operation:operation,params:'ID=' + id});
			
			var so = element.closest('.toolbar1,.content').prevAll('.search1');
			if (so.length)
				so.submit();
			
			if (callback)
				callback();
		}
		else
		{
			id = '';
			var element = $(element);
			if (element.parent().hasClass('toolbar1'))
				element.closest('.ali-navtab-panel').find('.ali-grid-body .ali-grid-row.ali-active').each(function(){id += id == '' ? $(this).data('id') : '|' + $(this).data('id');});
			else
				id = element.closest('tr').data('id');
			
			if (id == '')
			{
				ali.error(_lang_selection_empty);
				return;
			}
			
			operation = element.data('operation');
			if (operation == 'Delete')
				ali.confirm(_lang_confirm_delete, $.proxy(function(returnValue){if (returnValue)this.update(instance, object, element, id, operation, callback);}, this));
			else
				this.update(instance, object, element, id, operation, callback);
		}
	};

	function send(options)
	{
		options = $.extend({data:{},lang:_lang,type:'POST',statusMessage:_lang_working,silent:false}, options);

		var url = _webPath + 'alicms.aspx?Lang=' + options.lang + '&Object=' + options.object + '&Operation=' + options.operation;
		if (options.mark)
			url += '&Mark=' + options.mark;
		if (options.instance)
			url += '&Instance=' + options.instance;
		if (options.params)
			url += '&' + options.params;
		if (options.transfer)
			url += '&Transfer=' + encodeURIComponent(options.transfer);
		
		ali.working(options.statusMessage);

		var result = null;

		$.ajax(
		{
			url: url,
			data: options.data,
			type: options.type,
			async: false,
			error: function(jqXHR)
			{
				ali.error(_lang_operation_fail + '<br>' + unescape(jqXHR.responseText));
			},
			success: function(data)
			{
				if (!options.silent)
					ali.success(_lang_operation_success);
				result = data;
			}
		});
		
		return result;
	}

	this.isAllowedType = function(path, type)
	{
		if (!/^[A-Za-z]:\\/.test(path))
			return true;

		var ext = path.substr(path.lastIndexOf('.') + 1).toLowerCase();
		var types = type.toLowerCase().split('|');
		for (var i = 0; i < types.length; i++)
		{
			if (types[i] == ext)
				return true;
		}
		
		return false;
	};

	this.toAbsPanel = function(panel, path)
	{
		var index = panel.parent().children('.ali-navtab-panel').index(panel),
			base = ali.navTab('.ali-navtab', 'getUrl', index);

		return this.toAbsUrl(base, path);
	};
	
	this.toAbsUrl = function(base, path)
	{
		base = base.substr(0, base.lastIndexOf('/') + 1);
		
		var a = document.createElement('a')
		a.href = base + path;
		
		return a.href;
	};
	
	this.resizeContentBlock = function(panels)
	{
		$(panels).each(function()
		{
			var content = $('.content', $(this));
			if (content.length)
			{
				var parent = content.parent(),
					maxHeight = parent.height();
				content.siblings(':visible').each(function()
				{
					var me = $(this);
					var position = me.css('position');
	
					if (position === 'absolute' || position === 'fixed')
						return;
	
					maxHeight -= me.outerHeight(true);
				});
				content.height(maxHeight);
			}
		});
	}
	
	this.serialize = function(form)
	{
		//提前html编辑器内容填充到textarea上
		$('.editor', form).each(function()
		{
			this.value = CKEDITOR.instances[this.id].getData();
		});
		
		//上传组件如果需要上传，则不让序列化
		$('.ali-uploader', form).each(function()
		{
			if (ali.uploader(this, 'needUpload'))
				$(this).prev().prop('disabled', true);
		});
		
		var data = $(form).serialize();
		
		//上传组件取消禁用
		$('.ali-uploader', form).each(function()
		{
			$(this).prev().prop('disabled', false);
		});

		return data;
	};
		
	this.onDialogBeforeLoad = function(element, data)
	{
		data = data.match(/<section data-page="(.|\s)*?<\/section>/);
		if (!data) return;
		data = data[0];

		return data;
	}
	
	this.onDialogShow = function(element)
	{
		//设置标题
		ali.dialog(element, 'option', 'title', $('section', element).data('title'));
		
		//列表页面
		_helper.resizeContentBlock(element);
	
		//grid
		ali.grid($('[data-ali-widget=grid]', element));
		
		//combo
		ali.combo($('[data-ali-widget=combo]', element));

		//button
		ali.button($('.ali-button', element));

		//uploader
		ali.uploader($('.ali-uploader', element));

		//calendar
		ali.calendar($('[data-ali-widget=calendar]', element));
	}
}

function Index()
{
	this.init = function()
	{
		//实例化调度器
		_helper = new Helper();

		//ajax提交时，显示工作中
		$(document).ajaxStart(function(){ali.working(_lang_working);}).ajaxStop(function(){ali.working();});
		
		//设置侧栏默认宽度
		$('.frame1-left').data('width', 200);

		//设置菜单	
		ali.tabs('.menu', {event:'click', onActivate:onMenuActivate});

		//调整框架宽度
		onResize();
	
		//中栏设置为可拖放
		$('.frame1-mid').draggable(
		{
			axis: 'x',
			helper: 'clone',
			drag: function(e, ui)
			{
				var l = ui.offset.left;
				$('.frame1-right').width($('.frame1').width() - l - $('.frame1-mid').width());
				$('.frame1-left').width(l).data('width', l);
			}
		});
	
		//初始化界面部件
		ali.panel('.frame1-left>.ali-panel', {dir:'h',heightStyle:'fill',onBeforeToggle:onLeftNavExpand,onToggle:onResize});
		ali.accordion('.ali-accordion', {heightStyle:'fill'});
		ali.tree('.ali-tree');
		ali.navTab('.ali-navtab', {heightStyle:'fill',onBeforeLoad:onNavTabBeforeLoad,onLoad:onNavTabLoad});
		ali.tabs('.frame1 .ali-tabs');
	
		//绑定窗口大小变化事件
		$(window).bind('resize', onResize);
		
		//上传组件初始化
		ali.uploader(null, {url:_webPath + 'alicms.aspx'});
		
		//搜索
		$('.frame1-right')
						.on('submit', '.search1', onSearch)
						.on('submit', '.search2', onDialogSearch)
						.on('change', '.search1 select', function(){onSearch.call(this.form);onSearchSelectChange.call(this);})
						.on('click', '.search1 :checkbox', function(){onSearch.call(this.form);})
						.on('change', '.ali-navtab-panel>section>.content>.pagination1 [name=PageSize]', function(){var form = $(this).closest('.ali-navtab-panel').find('.search1');onSearch.call(form, $(this).closest('.pagination1').data('pageNumber'), this.value);})
						.on('click', '.ali-navtab-panel>section>.content>.pagination1 a', function(){var form = $(this).closest('.ali-navtab-panel').find('.search1');onSearch.call(form, $(this).attr('href'));return false;})
						.on('click', '.ali-navtab-panel>section>.content>.pagination1 .go button', function(){var p = $(this).prev();if (!p.val().match(/\d+/) || parseInt(p.val()) >= parseInt($(this).closest('.pagination1').data('pageCount'))){ali.error(_lang_page_number_incorrect, function(){p.select();});return;}var form = $(this).closest('.ali-navtab-panel').find('.search1');onSearch.call(form, p.val());})
						.on('click', '.ali-dialog-body .pagination1 a', function(){var form = $(this).closest('.ali-dialog-body').find('.search2');onDialogSearch.call(form, $(this).attr('href'));return false;})
						.on('click', '.toolbar1 .select-all', function(){var grid = $(this).parent().nextAll('.content').find('>.ali-grid');$('.ali-grid-row', grid).removeClass('ali-active').addClass('ali-active');})
						.on('click', '.toolbar1 .select-reverse', function(){var grid = $(this).parent().nextAll('.content').find('>.ali-grid');$('.ali-grid-row', grid).toggleClass('ali-active');});
	
		//处理hash
		if (location.hash != '')
		{
			var firstMenu = $('.menu a:first');
			if (firstMenu.length)
			{
				$('.frame1-left .ali-panel-header:first b').text(firstMenu.text());
				loadNav(firstMenu.data('id'));
			}
			ali.navTab('.ali-navtab', 'open', {title:'new tab',url:location.hash.substr(1)});
		}
		else
		{
			$('.menu a:first').click();//自动点击第一个菜单
		}
	};
	
	function onDialogSearch()
	{
		var pageNumber = 1;
		if (arguments.length > 0 && typeof(arguments[0]) != 'object')
			pageNumber = arguments[0];

		var param = '?Page=' + pageNumber,
			element = $(this).closest('.ali-dialog-body').children(),
			search2 = $('.search2', element),
			requires = $('.ali-input-required', search2);
		
		for (var i = 0; i < requires.length; i++)
		{
			if ($.trim(requires[i].value) == '')
			{
				ali.error(_lang_required, $.proxy(function(){requires[i].select();}, this));
				return false;
			}
		}

		$('select,:text,:checkbox', search2).each(function()
		{
			param += '&' + this.name + '=' + (this.type == 'checkbox' ? this.checked : encodeURIComponent(this.value));
		});
		
		var url = ali.dialog(element, 'option', 'url');
		ali.dialog(element, 'reload', {url:url + param, onBeforeLoad:function(element, data)
		{
			var m = data.match(/(<div class="content"[^>]*>)(.|\s)*?(<\/ul>|<\/table>)\s*<\/div>/);
			data = m[0].substr(m[1].length, m[0].length - m[1].length - 6);

			var content = $('.content', element).html(data);
			
			//grid
			ali.grid($('[data-ali-widget=grid]', content));

			//button
			ali.button($('.ali-button', element));

			return null;
		}});

		return false;
	}
	
	function onSearch()
	{
		var pageNumber = 1;
		if (arguments.length > 0 && typeof(arguments[0]) != 'object')
			pageNumber = arguments[0];

		var pageSize = 20;
		if (arguments.length > 1)
			pageSize = arguments[1];

		data = 'Page=' + pageNumber + '&PageSize=' + pageSize;
		
		$('select,:text,:checkbox', this).each(function()
		{
			data += '&' + this.name + '=' + (this.type == 'checkbox' ? this.checked : encodeURIComponent(this.value));
		});
		
		var form = $(this);
		var panel = form.closest('.ali-navtab-panel');
		var index = panel.parent().children('.ali-navtab-panel').index(panel);
		var navTab = panel.closest('.ali-navtab');
		var url = ali.navTab(navTab, 'getUrl', index);
		index = url.indexOf('?');
		if (index != -1)
			url = url.substr(0, index);
		url += '?' + data;
		ali.navTab(navTab, 'reload', null, {url:url, onBeforeLoad:function(element, index, data)
		{
			data = data.match(/<div class="content">(.|\s)*?(<\/ul>|<\/table>)\s*<\/div>/)[0];
			data = data.substr(21, data.length - 26);

			//把相对路径转换为绝对路径
			data = toAbsData(data, element, index);
			
			var content = form.nextAll('.content').html(data);
			
			//grid
			ali.grid($('[data-ali-widget=grid]', content));
			
			//combo
			ali.combo($('[data-ali-widget=combo]', content));
			
			//button
			ali.button($('.ali-button', content));

			location.hash = url;

			return null;
		}});
		return false;
	}
	
	function onSearchSelectChange()
	{
		var toolbar = $(this.form).nextAll('.toolbar1');
		if (this.name == 'IsRecycled')
		{
			if (this.value == 'true')
			{
				$('.recycle', toolbar).hide();
				$('.recover', toolbar).show();
				$('.delete', toolbar).show();
			}
			else if (this.value == 'false')
			{
				$('.recycle', toolbar).show();
				$('.recover', toolbar).hide();
				$('.delete', toolbar).hide();
			}
			else
			{
				$('.recycle', toolbar).hide();
				$('.recover', toolbar).hide();
				$('.delete', toolbar).hide();
			}
		}
		else if (this.name == 'IsRecommended')
		{
			if (this.value == 'true')
			{
				$('.recommend', toolbar).hide();
				$('.unrecommend', toolbar).show();
			}
			else if (this.value == 'false')
			{
				$('.recommend', toolbar).show();
				$('.unrecommend', toolbar).hide();
			}
			else
			{
				$('.recommend', toolbar).hide();
				$('.unrecommend', toolbar).hide();
			}
		}
		else if (this.name == 'IsHeld')
		{
			if (this.value == 'true')
			{
				$('.hold', toolbar).hide();
				$('.unhold', toolbar).show();
			}
			else if (this.value == 'false')
			{
				$('.hold', toolbar).show();
				$('.unhold', toolbar).hide();
			}
			else
			{
				$('.hold', toolbar).hide();
				$('.unhold', toolbar).hide();
			}
		}
	}
	
	function loadNav(parentID, url)
	{
		if (!url || url == '')
			url = 'nav.aspx';

		$.get(url + '?ParentID=' + parentID, function(data)
		{
			var $p = $('.frame1-left .ali-panel-body');
			var nav = data.match(/<section data-page="(.|\s)*?<\/section>/);
			$p.html(nav);
			$('section', $p).height($p.height());
			ali.tree($('.ali-tree', $p));
			ali.accordion($('.ali-accordion', $p));
			
			//通过html()写入内容的时候，href的地址在ie8以下版本中变成绝对地址，改回站内绝对地址
			if (ali.util.ie6 || ali.util.ie7)
			{
				$('section [href]', $p).each(function()
				{
					var host = 'http://' + document.location.host;
					var href = $(this).attr('href');
					if (href.indexOf(host) == 0)
						$(this).attr('href', href.substr(host.length));
				});
			}
			
			if (url != 'nav.aspx')
				_helper.init(null, null, url);
		});
	}
	
	function onMenuActivate(e, ui)
	{
		//修改侧栏标题
		$('.frame1-left .ali-panel-header:first b').text(ui.newTab.text());
		
		var a = $('>a', ui.newTab);
		var url = a.attr('href');
		if (url && url != '')
			ali.navTab('.ali-navtab', 'open', {url:url});
		
		//导入侧栏导航
		loadNav(a.data('id'), a.data('nav'));
		
		return false;
	}
	
	function onLeftNavExpand(ui, type)
	{
		if (type == 'collapse')
		{
			$('.frame1-mid').draggable('disable').css('cursor', 'default');
			return;
		}
		
		$('.frame1-mid').draggable('enable').css('cursor', 'col-resize');
	
		var l = $('.frame1-left').data('width');
		$('.frame1-right').width($('.frame1').width() - l - $('.frame1-mid').width());
		$('.frame1-left').width(l);
	}
	
	function onResize(ui, type)
	{
		//frame1宽度
		var w = $('html').width() - parseInt($('.frame1').css('padding-left').replace('px', '')) - parseInt($('.frame1').css('padding-right').replace('px', ''));
		$('.frame1').width(w);
	
		//frame1-left宽度
		var l;
		if (type == 'collapse')
			l = $('.frame1-left .ali-panel').outerWidth();
		else
			l = $('.frame1-left').data('width');
		$('.frame1-left').width(l);
		
		//frame1-right宽度
		$('.frame1-right').width(w - l - $('.frame1-mid').width());
		
		//frame1-left,frame1-mid和frame1-right高度
		var h = $('html').height() - $('.header1').height() - $('.menu').height() - parseInt($('.frame1').css('margin-top').replace('px', '')) - parseInt($('.frame1').css('margin-bottom').replace('px', ''));
		$('.frame1-left,.frame1-mid,.frame1-right').height(h);
		
		//触发resize事件
		$('.frame1-left>.ali-panel,.frame1-right>.ali-navtab').trigger('ali-resize');
		$('.frame1-left .ali-panel-body>section,.frame1-right>.ali-navtab>.ali-navtab-panel>section').each(function(){$(this).height($(this).parent().height())});
		resizePostBlock('.frame1-right>.ali-navtab>.ali-navtab-panel');
		_helper.resizeContentBlock('.frame1-right>.ali-navtab>.ali-navtab-panel');
		$('.frame1-right [data-ali-widget=grid]').trigger('ali-resize');
		$('.ali-accordion').trigger('ali-resize');
	}
	
	//提交表单页面重新计算高度
	function resizePostBlock(panels)
	{
		$(panels).each(function()
		{
			var post = $('.post', $(this));
			if (post.length)
			{
				var parent = post.parent(),
					maxHeight = parent.height();
				post.siblings(':visible').each(function()
				{
					var me = $(this);
					var position = me.css('position');
	
					if (position === 'absolute' || position === 'fixed')
						return;
	
					maxHeight -= me.outerHeight(true);
				});
				post.height(maxHeight);
				
				var h = maxHeight - $('>.post-footer', post).height();
				//if (h - 100 < $('>.post-body', post).height())
					$('>.post-body', post).height(h);
			}
		});
	}
	
	function toAbsData(data, element, index)
	{
		urls = [];
		var re = /href="([^"]*?)"\s+target="ali-navtab"/g,
			v;
		while ((v = re.exec(data)) != null)
		{
			if (v[1].match(/^(\/|http)/))
				continue;

			urls.push({start:v.index + 6,length:v[1].length});
		}
		
		var base = ali.navTab(element, 'getUrl', index);
		base = base.substr(0, base.lastIndexOf('/') + 1);
		for (var i = urls.length -1; i >= 0; i--)
		{
			var s = urls[i].start,
				l = urls[i].length;

			data = data.substr(0, s) + _helper.toAbsUrl(base, data.substr(s, l)) + data.substr(s + l);
		}
		
		return data;
	}
	
	//navTab加载url之前调用
	function onNavTabBeforeLoad(element, index, data)
	{
		data = data.match(/<section data-page="(.|\s)*?<\/section>/);
		if (!data) return;
		data = data[0];

		//把相对路径转换为绝对路径
		data = toAbsData(data, element, index);

		return data;
	}
	
	//navTab加载url之后调用
	function onNavTabLoad(element, index)
	{
		var $p = ali.navTab(element, 'getPanel', index);
		
		$('section', $p).height($p.height());
		ali.navTab(element, 'setTitle', index, $('section', $p).data('title'));
		
		//提交表单（添加，编辑）
		resizePostBlock($p);
		
		//列表页面
		_helper.resizeContentBlock($p);
		
		//处理搜索表单状态
		$.each(queryToArray(ali.navTab(element, 'getUrl', index)), function()
		{
			var element = $('[name=' + this.name + ']', $p);
			if (!element.length)
				return true;

			if ((element[0].tagName == 'INPUT' && element[0].type == 'text') || element[0].tagName == 'SELECT')
				element.val(this.value);
			
			if (element[0].tagName == 'INPUT' && element[0].type == 'checkbox')
				element[0].checked = this.value.toLowerCase() == 'true' ? true : false;
		});

		//accordion
		ali.accordion($('.ali-accordion', $p));
		
		//button
		ali.button($('.ali-button', $p));
		
		//calendar
		ali.calendar($('[data-ali-widget=calendar]', $p));
		
		//menu
		ali.menu($('.ali-menu', $p));
		
		//navTab
		ali.navTab($('.ali-navtab', $p), {target:'ali-navtab-test'});
		
		//tree
		ali.tree($('.ali-tree', $p));
		
		//grid
		ali.grid($('[data-ali-widget=grid]', $p));
		
		//combo
		ali.combo($('[data-ali-widget=combo]', $p));
		
		//uploader
		ali.uploader($('.ali-uploader', $p));
		
		//panel
		ali.panel($('.ali-panel', $p));
		
		//tabs
		ali.tabs($('.ali-tabs', $p));
		
		//html editor
		var editors = $('.editor,.editor-basic', $p);
		if (editors.length)
		{
			/* ckeditor*/
			if ($('script[src*=ckeditor]').length == 0)
				$('body').append('<script src="' + _commonPath + 'ckeditor/ckeditor.js"></script>');
			
			editors.each(function()
			{
				this.id = ali.util.formatDate(new Date(), 'SSS');
				var config = {};
				if ($(this).hasClass('editor-basic'))
					config.toolbar = 'Basic';

				if ($(this).data('lang') == 'UYG')
					config.language = 'ug';
				else
					config.language = 'zh-cn';

				if (typeof($(this).data('browseUrl')) != 'undefined')
				{
					config.filebrowserBrowseUrl = $(this).data('browseUrl');
					config.filebrowserImageBrowseUrl = $(this).data('browseUrl') + '&ListByPicture=true';
				}

				CKEDITOR.replace(this.id, config);
			});
			/**/
			
			/* ueditor 
			if ($('script[src*=ueditor]').length == 0)
				$('body').append('<script src="' + _commonPath + 'ueditor/ueditor.config.js"></script><script src="' + _commonPath + 'ueditor/ueditor.all.min.js"></script>');
			
			editors.each(function()
			{
				var me = $(this);
				var ue = UE.getEditor(this);
				ue.ready(function()
				{
					 ue.execCommand('serverparam', {'instance':me.data('instanceId'),'lang':_lang});
				});
			});
			/**/
		}
		
		//处理toolbar状态
		$('.search1 select', $p).each(onSearchSelectChange);
		
		//处理js
		_helper.init(element, index);
	}
	
	//将URL中的QueryString转换为对象数组
	function queryToArray(url)
	{
		var result = [];

		var index = url.indexOf('?');
		if (index == -1)
			return result;
		
		var query = url.substr(index + 1),
			kvs = query.split('&');
		
		for (var i in kvs)
		{
			var kv = kvs[i].split('=');
			result.push({name:kv[0],value:kv[1]});
		}
		
		return result;
	}
}

function Register()
{
	this.Name_onChange = function()
	{
		var me = $(this);
	
		if (me.val() == '')
		{
			me.addClass('ali-input-error').nextAll('strong').addClass('error').html(_lang_name_empty);
			return;
		}
	
		if(!/^[a-zA-Z0-9]{5,20}$/.test(me.val()))
		{
			me.addClass('ali-input-error').nextAll('strong').addClass('error').html(_lang_name_incorrect);
			return;
		}
	
		$.get(_webPath + 'alicms.aspx?Object=User&Operation=IsNameExist&Name=' + encodeURIComponent(me.val()),function(data)
		{
			if (data.toLowerCase() == 'true')
				me.addClass('ali-input-error').nextAll('strong').addClass('error').html(_lang_name_exist);
			else
				me.removeClass('ali-input-error').nextAll('strong').removeClass('error').html(me.attr('title'));
		});
	};

	this.Password_onChange = function()
	{
		var me = $(this);
	
		if (me.val() == '')
		{
			me.addClass('ali-input-error').nextAll('strong').addClass('error').html(_lang_password_empty);
			return;
		}
		
		if(!/^[a-zA-Z0-9]{6,20}$/.test(me.val()))
			me.addClass('ali-input-error').nextAll('strong').addClass('error').html(_lang_password_incorrect);
		else
			me.removeClass('ali-input-error').nextAll('strong').removeClass('error').html(me.attr('title'));
	};

	this.Confirm_onChange = function()
	{
		var me = $(this);
	
		if (me.val() != $('[name=Password]').val())
			me.addClass('ali-input-error').nextAll('strong').addClass('error').html(_lang_password_nosame);
		else
			me.removeClass('ali-input-error').nextAll('strong').removeClass('error').html(me.attr('title'));
	};

	this.Mobile_onChange = function()
	{
		var me = $(this);
	
		if (me.val() == '')
		{
			me.removeClass('ali-input-error').nextAll('strong').removeClass('error').html(me.attr('title'));
			return;
		}
		
		if (!ali.util.isMobile(me.val()))
		{
			me.addClass('ali-input-error').nextAll('strong').addClass('error').html(_lang_mobile_incorrect);
			return;
		}
		
		$.get(_webPath + 'alicms.aspx?Object=User&Operation=IsMobileExist&Mobile=' + encodeURIComponent(me.val()),function(data)
		{
			if (data.toLowerCase() == 'true')
				me.addClass('ali-input-error').nextAll('strong').addClass('error').html(_lang_mobile_exist);
			else
				me.removeClass('ali-input-error').nextAll('strong').removeClass('error').html(me.attr('title'));
		});
	};

	this.Email_onChange = function()
	{
		var me = $(this);
	
		if (me.val() == '')
		{
			me.removeClass('ali-input-error').nextAll('strong').removeClass('error').html(me.attr('title'));
			return;
		}
		
		if(!ali.util.isEmail(me.val()))
		{
			me.addClass('ali-input-error').nextAll('strong').addClass('error').html(_lang_email_incorrect);
			return;
		}
	
		$.get(_webPath + 'alicms.aspx?Object=User&Operation=IsEmailExist&Email=' + encodeURIComponent(me.val()),function(data)
		{
			if (data.toLowerCase() == 'true')
				me.addClass('ali-input-error').nextAll('strong').addClass('error').html(_lang_email_exist);
			else
				me.removeClass('ali-input-error').nextAll('strong').removeClass('error').html(me.attr('title'));
		});
	};

	this.register = function()
	{
		//检查用户名
		if (this.Name.value == '')
		{
			$(this.Name).addClass('ali-input-error');
			ali.error(_lang_name_empty, $.proxy(function(){this.Name.select();}, this));
			return false;
		}
	
		if (!this.Name.value.match(/^[a-zA-Z0-9]{5,20}$/))
		{
			ali.error(_lang_name_incorrect, $.proxy(function(){this.Name.select();}, this));
			return false;
		}
	
		$(this.Name).removeClass('ali-input-error');
		
		//检查密码
		if (this.Password.value == '')
		{
			$(this.Password).addClass('ali-input-error');
			ali.error(_lang_password_empty, $.proxy(function(){this.Password.select();}, this));
			return false;
		}
		
		if (!this.Password.value.match(/^[a-zA-Z0-9]{6,20}$/))
		{
			$(this.Password).addClass('ali-input-error');
			ali.error(_lang_password_incorrect, $.proxy(function(){this.Password.select();}, this));
			return false;
		}
	
		$(this.Password).removeClass('ali-input-error');
	
		if (this.Confirm.value != this.Password.value)
		{
			$(this.Confirm).addClass('ali-input-error');
			ali.error(_lang_password_nosame, $.proxy(function(){this.Confirm.select();}, this));
			return false;
		}
	
		$(this.Confirm).removeClass('ali-input-error');
	
		//检查手机
		if (this.Mobile.value != '' && !ali.util.isMobile(this.Mobile.value))
		{
			$(this.Mobile).addClass('ali-input-error');
			ali.error(_lang_mobile_incorrect, $.proxy(function(){this.Mobile.select();}, this));
			return false;
		}
	
		$(this.Mobile).removeClass('ali-input-error');
		
		//检查电子邮件
		if (this.Email.value != '' && !ali.util.isEmail(this.Email.value))
		{
			$(this.Email).addClass('ali-input-error');
			ali.error(_lang_email_incorrect, $.proxy(function(){this.Email.select();}, this));
			return false;
		}
	
		$(this.Email).removeClass('ali-input-error');
	
		$(':submit')[0].disabled = true;
		ali.working(_lang_working);
		
		register_checkName(this);	
		
		return false;
	};

	function register_checkName(form)
	{
		$.get(_webPath + 'alicms.aspx?Object=User&Operation=IsNameExist&Name=' + encodeURIComponent(form.Name.value),function(data)
		{
			if (data.toLowerCase() == 'true')
			{
				ali.error(_lang_name_exist, function(){form.Name.select();});
				$(':submit')[0].disabled = false;
				ali.working();
			}
			else
			{
				register_checkMobile(form);
			}
		});
	}

	function register_checkMobile(form)
	{
		if (form.Mobile.value == '')
		{
			register_checkEmail(form);
			return;
		}
	
		$.get(_webPath + 'alicms.aspx?Object=User&Operation=IsMobileExist&Mobile=' + encodeURIComponent(form.Mobile.value),function(data)
		{
			if (data.toLowerCase() == 'true')
			{
				ali.error(_lang_mobile_exist, function(){form.Mobile.select();});
				$(':submit')[0].disabled = false;
				ali.working();
			}
			else
			{
				register_checkEmail(form);
			}
		});
	}

	function register_checkEmail(form)
	{
		if (form.Email.value == '')
		{
			register_Send(form);
			return;
		}
	
		$.get(_webPath + 'alicms.aspx?Object=User&Operation=IsEmailExist&Email=' + encodeURIComponent(form.Email.value),function(data)
		{
			if (data.toLowerCase() == 'true')
			{
				ali.error(_lang_email_exist, function(){form.Email.select();});
				$(':submit')[0].disabled = false;
				ali.working();
			}
			else
			{
				register_Send(form);
			}
		});
	}

	function register_Send(form)
	{
		var data = 'IsChecked=' + !_isNeedToCheck + '&Name=' + encodeURIComponent(form.Name.value);
		data += '&Password=' + encodeURIComponent(form.Password.value);
		data += '&Mobile=' + encodeURIComponent(form.Mobile.value);
		data += '&Email=' + encodeURIComponent(form.Email.value);
		
		$.ajax(
		{
			url: _webPath + 'alicms.aspx?Object=User&Operation=Register',
			data: data,
			type: 'POST',
			error: function()
			{
				ali.error(_lang_operation_fail);
				$(':submit')[0].disabled = false;
				ali.working();
			},
			success: function(data)
			{
				data = 'Name=' + encodeURIComponent(form.Name.value);
				data += '&Password=' + encodeURIComponent(form.Password.value);
	
				$.ajax(
				{
					url: _webPath + 'alicms.aspx?Object=User&Operation=Login',
					data: data,
					type: 'POST',
					complete: function()
					{
						window.location.replace(_step2 + '?Name=' + encodeURIComponent(form.Name.value) + '&Email=' + encodeURIComponent(form.Email.value));
					}
				});
			}
		});
	}

	this.sendEmailValidation = function()
	{
		var data = 'Name=' + encodeURIComponent(_name) + '&ValidateUrl=' + encodeURIComponent(_validateUrl)
		
		ali.working(_lang_sending_validation_mail);
	
		$.ajax(
		{
			url: _webPath + 'alicms.aspx?Object=User&Operation=SendEmailValidation',
			data: data,
			type: 'POST',
			error: function()
			{
				ali.error(_lang_operation_fail);
				ali.working();
			},
			success: function(data)
			{
				ali.success(_lang_operation_success, {modal:true});
				ali.working();
				
				$('.register button i').html(_lang_resend);
			}
		});
	};
}

function Login()
{
	this.login = function()
	{
		if ($.trim(this.Name.value) == '' || $(this).data('tip') == this.Name.value)
		{
			ali.error(_lang_name_empty, $.proxy(function(){this.Name.select();}, this));
			return false;
		}
		
		if ($.trim(this.Password.value) == '')
		{
			ali.error(_lang_password_empty, $.proxy(function(){this.Password.select();}, this));
			return false;
		}
		
		if (this.CheckCode != null && $.trim(this.CheckCode.value) == '')
		{
			ali.error(_lang_check_code_empty, $.proxy(function(){this.CheckCode.select();}, this));
			return false;
		}
		
		var data = 'Name=' + encodeURIComponent(this.Name.value);
		data += '&Password=' + encodeURIComponent(this.Password.value);
		if (this.CheckCode != null)
			data += '&CheckCode=' + encodeURIComponent(this.CheckCode.value);
		if ($('#remember')[0].checked)
			data += "&Minutes=" + (60*24*365);
		
		ali.working(_lang_working);
		$(':submit')[0].disabled = true;
	
		$.ajax(
		{
			url: _webPath + 'alicms.aspx?Object=User&Operation=Login',
			data: data,
			type: 'POST',
			error: function()
			{
				ali.error(_lang_login_fail);
				$('#check-code-image').attr('src', _webPath + 'alicms.aspx?Action=CheckCode&' + Math.random());
				ali.working();
				$(':submit')[0].disabled = false;
			},
			success: function()
			{
				if (_loginPath == '')
				{
					if (_referer == '')
						window.location = window.location.href.replace('login', 'index');
					else
						window.location = _referer;
				}
				else
				{
					_loginPath = _loginPath.replace('{ChannelPath}', _channelPath);

					$.ajax(
					{
						url: _loginPath,
						data: data,
						type: 'POST',
						error: function()
						{
							ali.error(_lang_login_fail);
							$('#check-code-image').attr('src', _webPath + 'alicms.aspx?Action=CheckCode&' + Math.random());
							ali.working();
							$(':submit')[0].disabled = false;
						},
						success: function(userRoles)
						{
							if (_adminRole == '')
							{
								if (_referer == '')
									window.location = window.location.href.replace('login', 'index');
								else
									window.location = _referer;
							}
							else
							{
								var hasRight = false;
								userRoles = userRoles.split('|');
								for (var i = 0; i < userRoles.length; i++)
								{
									if (userRoles[i].indexOf(_adminRole) != -1)
									{
										hasRight = true;
										break;
									}
								}
								
								if (hasRight)
								{
									if (_referer == '')
										window.location = window.location.href.replace('login', 'index');
									else
										window.location = _referer;
								}
								else
								{
									ali.error(_lang_login_fail);
									$('#check-code-image').attr('src', _webPath + 'alicms.aspx?Action=CheckCode&' + Math.random());
									ali.working();
									$(':submit')[0].disabled = false;
								}
							}
						}
					});
				}
			}
		});
		return false;
	};
	
	this.check = function()
	{
		if (ali.util.cookie('UserID') != '' && ali.util.cookie('Namespace') != 'AliCMS.SystemModule')
		{
			if (_loginPath == '')
			{
				$('#user-name').text(ali.util.cookie('UserName'));
				$('.login-right .ali-panel-body>div,.login-right form table').toggle();
			}
			else
			{
				$.ajax(
				{
					url: _loginPath,
					data: data,
					type: 'POST',
					success: function(userRoles)
					{
						if (_adminRole == '')
						{
							$('#user-name').text(ali.util.cookie('UserName'));
							$('.login-right .ali-panel-body>div,.login-right form table').toggle();
						}
						else
						{
							var hasRight = false;
							userRoles = userRoles.split('|');
							for (var i = 0; i < userRoles.length; i++)
							{
								if (userRoles[i].indexOf(_adminRole) != -1)
								{
									hasRight = true;
									break;
								}
							}
							
							if (hasRight)
							{
								$('#user-name').text(ali.util.cookie('UserName'));
								$('.login-right .ali-panel-body>div,.login-right form table').toggle();
							}
						}
					}
				});
			}
		}
	};
	
	this.onQQLoginClick = function()
	{
		window.open('https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=' + _qq_connect_app_id + '&redirect_uri=' + encodeURIComponent(_connect_qq_result_path) + '&state=AliCMS','TencentLogin','width=700,height=500,menubar=0,scrollbars=1,resizable=1,status=1,titlebar=0,toolbar=0,location=1');
	};
}

function FindPassword()
{
	this.checkName = function()
	{
		if (this.Name.value == '')
		{
			ali.error(_lang_name_empty, $.proxy(function(){this.Name.select();}, this));
			return false;
		}
		
		return true;
	};
	
	this.sendFindPasswordMail = function()
	{
		var data = 'Name=' + encodeURIComponent(_name) + '&ValidateUrl=' + encodeURIComponent(_validateUrl)
		
		ali.working(_lang_sending_mail);
	
		$.ajax(
		{
			url: _webPath + 'alicms.aspx?Object=User&Operation=SendFindPasswordMail',
			data: data,
			type: 'POST',
			error: function()
			{
				ali.error(_lang_operation_fail);
				ali.working();
			},
			success: function()
			{
				ali.success(_lang_operation_success, {modal:true});
				ali.working();
			}
		});
	};
	
	this.modifyPassword = function()
	{
		if (this.NewPassword.value == '')
		{
			ali.error(_lang_new_password_empty, $.proxy(function(){this.NewPassword.select();}, this));
			return false;
		}
		
		var data = 'NewPassword=' + encodeURIComponent(this.NewPassword.value) + '&ValidationString=' + encodeURIComponent(this.ValidationString.value)
		
		ali.working(_lang_working);
	
		$.ajax(
		{
			url: _webPath + 'alicms.aspx?Object=User&Operation=ModifyPassword',
			data: data,
			type: 'POST',
			error: function()
			{
				ali.error(_lang_operation_fail);
				ali.working();
			},
			success: function()
			{
				ali.success(_lang_operation_success, {modal:true,onClose:function(){window.location = _loginPath;}});
				ali.working();
			}
		});
		
		return false;
	};
}

function QQConnect()
{
	this.qqLogin = function()
	{
		ali.working(_lang_logining);
	
		$.ajax(
		{
			url: _webPath + 'alicms.aspx?Object=User&Operation=QQLogin',
			data: 'AuthorizationCode=' + _authorizationCode,
			type: 'POST',
			error: function()
			{
				ali.error(_lang_login_fail, function()
				{
					window.opener.location.reload();
					window.close();
				});
			},
			success: function(result)
			{
				ali.working();

				if (result == '1')
				{
					ali.success(_lang_create_or_bind, {modal:true});
					$('.block2').show();
					ali.tabs('.ali-tabs', {event:'click'});
					ali.button('.ali-button');
					$('form:first').submit(qqRegister);
					$('form:last').submit(qqBind);
				}
				else
				{
					window.opener.location.reload();
					window.close();
				}
			}
		});
	};
	
	function qqRegister()
	{
		//检查用户名
		if (this.Name.value == '')
		{
			ali.error(_lang_name_empty, $.proxy(function(){this.Name.select();}, this));
			return false;
		}
	
		if (!this.Name.value.match(/^[a-zA-Z0-9]{5,20}$/))
		{
			ali.error(_lang_name_incorrect, $.proxy(function(){this.Name.select();}, this));
			return false;
		}
		
		//检查密码
		if (this.Password.value == '')
		{
			ali.error(_lang_password_empty, $.proxy(function(){this.Password.select();}, this));
			return false;
		}
		
		if (!this.Password.value.match(/^[a-zA-Z0-9]{6,20}$/))
		{
			ali.error(_lang_password_incorrect, $.proxy(function(){this.Password.select();}, this));
			return false;
		}
	
		$(':submit', this)[0].disabled = true;
		ali.working(_lang_working);

		//检查名称是否存在
		var isNameExist = null;

		$.ajax(
		{
			url: _webPath + 'alicms.aspx?Object=User&Operation=IsNameExist&Name=' + encodeURIComponent(this.Name.value),
			type: 'GET',
			async: false,
			error: function()
			{
				ali.error(_lang_operation_fail);
				ali.working();
			},
			success: function(data)
			{
				if (data.toLowerCase() == 'true')
					isNameExist = true;
				else
					isNameExist = false;
			}
		});
		
		if (isNameExist == null)
		{
			ali.working();
			$(':submit', this)[0].disabled = false;
			return false;
		}
		
		if (isNameExist)
		{
			ali.error(_lang_name_exist);
			ali.working();
			$(':submit', this)[0].disabled = false;
			this.Name.select();
			return false;
		}
		
		var form = this;
		var data = '&Name=' + encodeURIComponent(form.Name.value);
		data += '&Password=' + encodeURIComponent(form.Password.value);
		
		$.ajax(
		{
			url: _webPath + 'alicms.aspx?Object=User&Operation=Register',
			data: data,
			type: 'POST',
			error: function(jqXHR)
			{
				ali.error(_lang_operation_fail + '<br>' + unescape(jqXHR.responseText));
				$(':submit', form)[0].disabled = false;
				ali.working();
			},
			success: function(data)
			{
				data = 'Name=' + encodeURIComponent(form.Name.value);
				data += '&Password=' + encodeURIComponent(form.Password.value);
	
				$.ajax(
				{
					url: _webPath + 'alicms.aspx?Object=User&Operation=Login',
					data: data,
					type: 'POST',
					complete: function()
					{
						window.opener.location.reload();
						window.close();
					}
				});
			}
		});
		
		return false;
	};
	
	function qqBind()
	{
		if ($.trim(this.Name.value) == '')
		{
			ali.error(_lang_name_empty, $.proxy(function(){this.Name.select();}, this));
			return false;
		}
		
		if ($.trim(this.Password.value) == '')
		{
			ali.error(_lang_password_empty, $.proxy(function(){this.Password.select();}, this));
			return false;
		}
		
		var data = 'Name=' + encodeURIComponent(this.Name.value);
		data += '&Password=' + encodeURIComponent(this.Password.value);
		
		ali.working(_lang_working);
		$(':submit', this)[0].disabled = true;
	
		$.ajax(
		{
			url: _webPath + 'alicms.aspx?Object=User&Operation=QQBind',
			data: data,
			type: 'POST',
			error: function(jqXHR)
			{
				ali.error(_lang_operation_fail + '<br>' + unescape(jqXHR.responseText));
				ali.working();
				$(':submit')[0].disabled = false;
			},
			success: function()
			{
				window.opener.location.reload();
				window.close();
			}
		});
		return false;
	};
}

(function()
{
	if (_page == 'index')
	{
		var index = new Index();
		index.init();
	}
	else if (_page == 'register')
	{
		var register = new Register();

		ali.panel('.ali-panel');
		ali.button('.ali-button');
		
		$('[name=Name]').blur(register.Name_onChange);
		$('[name=Password]').blur(register.Password_onChange);
		$('[name=Confirm]').blur(register.Confirm_onChange);
		$('[name=Mobile]').blur(register.Mobile_onChange);
		$('[name=Email]').blur(register.Email_onChange);
		$('form').submit(register.register);
	}
	else if (_page == 'register_step2')
	{
		var register = new Register();

		ali.panel('.ali-panel');
		ali.button('.ali-button');
		$('.register button').click(register.sendEmailValidation);
	}
	else if (_page == 'register_step3')
	{
		ali.panel('.ali-panel');
	}
	else if (_page == 'login')
	{
		//界面元素
		ali.panel('.ali-panel', {heightStyle:'fill'});
		ali.button('.ali-button');
		
		//输入框焦点事件
		$('form [name=Name]').data('tip', $('form [name=Name]').val()).focus(function()
		{
			var me = $(this);
			if (me.data('tip') == me.val())
			{
				me.val('');
				me.toggleClass('tip');
			}
		}).blur(function()
		{
			var me = $(this);
			if (me.val() == '')
			{
				me.val(me.data('tip'));
				me.toggleClass('tip');
			}
		});
		
		//验证码
		$('#check-code-image').click(function(){$(this).attr('src', _webPath + 'alicms.aspx?Action=CheckCode&' + Math.random());});
		
		//登录表单提交事件
		var login = new Login();
		$('form').submit(login.login);
		$('#qqlogin').click(login.onQQLoginClick);
		login.check();
	}
	else if (_page == 'find_password')
	{
		ali.panel('.ali-panel');
		ali.button('.ali-button');

		var findPassword = new FindPassword();
		$('form').submit(findPassword.checkName);
	}
	else if (_page == 'find_password_step2')
	{
		ali.panel('.ali-panel');
		ali.button('.ali-button');

		var findPassword = new FindPassword();
		$('.register button').click(findPassword.sendFindPasswordMail);
		findPassword.sendFindPasswordMail();
	}
	else if (_page == 'find_password_step3')
	{
		ali.panel('.ali-panel');
		ali.button('.ali-button');

		var findPassword = new FindPassword();
		$('form').submit(findPassword.modifyPassword);
	}
	else if (_page == 'qqconnect')
	{
		var qqconnect = new QQConnect();
		qqconnect.qqLogin();
	}
})();